package com.zelin;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.Test;

import java.util.Date;

/**
 * Created by WF on 2019/9/23 10:09
 * jwt的基本用法2
 */
public class JwtDemo03 {

    //1.测试生成token的方法(设置过期时间+携带数据)
    @Test
    public void test01(){
        //1.1)定义一个jwtBuilder
        //说明：
        //1.Jwts.builder():代表jwt生成器
        //2.setId():设置生成器的id
        //3.setIssuedAt():设置加密时间
        //4.setSubject():设置主体信息
        //signWith:设置jwt的签名
        //5.compact()：得到jwt生成的字符串
        //6.setExpiration():设置过期时间
        long l = System.currentTimeMillis();        //得到当前时间距离1970-1-1以来的毫秒数
        Date date = new Date(l + 300 * 1000);       //设置到期时间为5分钟后

        JwtBuilder jwtBuilder = Jwts.builder().setId("8888")
                .setIssuedAt(new Date())
                .setSubject("admin")
                .setExpiration(date)
                .claim("roles","admin")
                .signWith(SignatureAlgorithm.HS256, "zelin");
        //1.2）生成token对象
        String token = jwtBuilder.compact();
        //1.3)打印
        System.out.println(token);

    }
    //2.解析token(过期时间+携带数据 )
    @Test
    public void test02(){
        //2.1)定义要解析的token字符串
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODg4IiwiaWF0IjoxNTY5MjA1NjgyLCJzdWIiOiJhZG1pbiIsImV4cCI6MTU2OTIwNTk4MSwicm9sZXMiOiJhZG1pbiJ9.c-lDed3ZN1xMc1U03Wm5f5XGMcYp8rSyY87soPCgK1c";
        //2.2)解析token
        Claims claims = Jwts.parser().setSigningKey("zelin").parseClaimsJws(token).getBody();
        String id = claims.getId();
        Date issuedAt = claims.getIssuedAt();
        String subject = claims.getSubject();
        Date expiration = claims.getExpiration();
        String roles = (String) claims.get("roles");
        System.out.println("id = " + id);
        System.out.println("issuedAt = " + issuedAt);
        System.out.println("subject = " + subject);
        System.out.println("expiration = " + expiration);
        System.out.println("roles = " + roles);

    }
}

